package action;

import java.io.IOException;
import java.util.ArrayList;

import rmi.ComManager;
import servlet.GameSession;
import servlet.MastermindServlet;
import bean.DeconnectionMessage;
import bean.Message;
import bean.PlayMessage;

public class ActionPlay extends MastermindServlet implements Action{
	PlayMessage mOut;
	public ActionPlay(Message m){
		mOut = (PlayMessage)m; 
	}
	public Message call(){		
		try {
			return execute();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}	
	}
	public Message execute() throws IOException{
		mOut = (PlayMessage)mOut;
		GameSession gs = listGameSessions.get(mOut.getIdUser());
		gs.setPlayCount(gs.getPlayCount()+1);
		mOut.setNbBlancs(0);
		mOut.setNbNoirs(0);
		
		ArrayList<Integer> soluce =new ArrayList<Integer>() ;
		
	
		soluce.add(gs.getCombi().getP1());
		soluce.add(gs.getCombi().getP2());
		soluce.add(gs.getCombi().getP3());
		soluce.add(gs.getCombi().getP4());
	
		ArrayList<Integer> combi = new ArrayList<Integer>();
		combi.add(mOut.getCombi().getP1());
		combi.add(mOut.getCombi().getP2());
		combi.add(mOut.getCombi().getP3());
		combi.add(mOut.getCombi().getP4());
		
		ArrayList<Integer> indexFindListSol = new ArrayList<Integer>();
		ArrayList<Integer> indexFindListComb = new ArrayList<Integer>();
		
		for(int i=0; i<4; i++)
		{
			if(soluce.get(i).equals(combi.get(i)))
			{
				mOut.setNbNoirs(mOut.getNbNoirs()+1);
				indexFindListSol.add(i);
				indexFindListComb.add(i);
			}
			else if (gs.getPlayCount() == Integer.parseInt(config.getProperty("maxPlay"))) {
				mOut.setPerdu(true);
				DeconnectionMessage dm = new DeconnectionMessage();
				dm.setIdUser(mOut.getIdUser());
				ActionDeconnection ad = new ActionDeconnection(dm);
				ad.call();
			}
		}
		
		for(int i=0; i<4; i++)
		{
			for(int j=0; j<4; j++)
			{
				if(soluce.get(j).equals(combi.get(i)) && !indexFindListComb.contains(i) && !indexFindListSol.contains(j))
				{
					mOut.setNbBlancs(mOut.getNbBlancs()+1);
					indexFindListSol.add(j);
					indexFindListComb.add(i);
				}
			}
		}		
		if (mOut.getNbNoirs()==4) {
			mOut.setCombi(gs.getCombi());
			saveWin(mOut);
			DeconnectionMessage dm = new DeconnectionMessage();
			dm.setIdUser(mOut.getIdUser());
			ActionDeconnection ad = new ActionDeconnection(dm);
			ad.call();
	
		}
		return mOut;
	}
	
	private void saveWin(Message mOut){
		
		ComManager com = new ComManager();
		com.comRmi(mOut);
	}
	
}
